package com.archetypus.projectschedule.common;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;

public class ServiceLocator {

	private static ServiceLocator serviceLocator;
	InitialContext initialContext = null;

	private ServiceLocator() throws ServiceLocatorException {
		try {
			initialContext = new InitialContext();
		} catch (NamingException ne) {
			throw new ServiceLocatorException();
		}
	}

	public synchronized static ServiceLocator getInstance()
			throws ServiceLocatorException {
		if (serviceLocator == null) {
			serviceLocator = new ServiceLocator();
		}
		return serviceLocator;
	}

	public Object lookup(String jndiName) throws ServiceLocatorException {
		Object object = null;
		try {

			if (Configuration.getInstance().get("targetPlatform")
					.equalsIgnoreCase("TOMCAT")) {
				Context envCtx = (Context) initialContext
						.lookup("java:comp/env");
				object = envCtx.lookup(jndiName);
			} else if (Configuration.getInstance().get("targetPlatform")
					.equalsIgnoreCase("JBOSS")) {
				object = initialContext.lookup(jndiName);
			} else {
				throw new ServiceLocatorException(
						"Not exists the target platform");
			}

		} catch (NamingException e) {
			e.printStackTrace();
			throw new ServiceLocatorException();
		}

		return object;
	}

	public UserTransaction lookupUserTransaction()
			throws ServiceLocatorException {
		UserTransaction userTransaction = null;
		try {
			if (Configuration.getInstance().get("targetPlatform")
					.equalsIgnoreCase("TOMCAT")) {
				userTransaction = (UserTransaction) initialContext
						.lookup("java:comp/env/UserTransaction");
			} else if (Configuration.getInstance().get("targetPlatform")
					.equalsIgnoreCase("JBOSS")) {

				userTransaction = (UserTransaction) initialContext
						.lookup("UserTransaction");
			} else {
				throw new ServiceLocatorException(
						"Not exists the target platform");
			}

		} catch (NamingException e) {
			e.printStackTrace();
			throw new ServiceLocatorException();
		}

		return userTransaction;
	}
}
